﻿// Write a program to convert binary numbers to their decimal representation.

using System;

public class BinToDec
{
    static void Main()
    {
        Console.Write("Enter binary number (or leave empty for Random): ");
        string binaryNumberString = Console.ReadLine();
        if (string.IsNullOrEmpty(binaryNumberString))
        {
            Random random = new Random();
            int decimalNumber = random.Next(int.MinValue, int.MaxValue);
            binaryNumberString = Convert.ToString(decimalNumber, 2).PadLeft(32, '0');
            Console.WriteLine("Generated Random numbers is: {0}", binaryNumberString);
        }

        Console.WriteLine("Decimal representation is : {0}", ToDecimal(binaryNumberString));
        Console.WriteLine("Decimal number for control: {0}", Convert.ToInt32(binaryNumberString, 2));
    }

    public static int ToDecimal(string binaryNumberString)
    {
        int sum = 0;
        char[] binaryNumberArray = binaryNumberString.ToCharArray();
        for (int i = binaryNumberArray.Length - 1, power = 0; i >= 0; i--, power++)
        {
            //sum += int.Parse(binaryNumberArray[i].ToString()) * (int)Math.Pow(2, power);
            sum += int.Parse(binaryNumberArray[i].ToString()) * Pow(2, power);
        }

        return sum;
    }

    public static int Pow(int number, int power)
    {
        int result = 1;
        for (int i = 0; i < power; i++)
        {
            result *= number;
        }

        return result;
    }
}